/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.smtpserver.contenthandler;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.james.mime4j.AbstractContentHandler;
import org.apache.james.mime4j.field.Field;
import org.apache.james.mime4j.field.UnstructuredField;
import org.springframework.beans.factory.annotation.Required;

public class BannedAttachmentContentHandler extends AbstractContentHandler {

    private static final Pattern P = Pattern
            .compile(".*filename=(\".*?\"|[^\\s]*).*");

    private boolean banned = false;

    private String bannedExtension = null;

    private List<String> extensions;

    @Required
    public void setBannedAttachmentExtension(List<String> extensions) {
        this.extensions = extensions;
    }

    /**
     * Return true if a banned attachment extension was found
     * 
     * @return
     */
    public boolean isBannedAttachment() {
        return banned;
    }

    /**
     * Return the banned attachment extension which was found
     * 
     * @return extension
     */
    public String getBannedExtension() {
        return bannedExtension;
    }

    @Override
    public void field(String fieldData) {
        if (fieldData.toLowerCase().startsWith("content-disposition:")) {
            UnstructuredField field = (UnstructuredField) Field
                    .parse(fieldData);
            Matcher m = P.matcher(field.getValue());
            if (m.matches()) {
                String filename = m.group(1);
                String parts[] = filename.substring(1, filename.length() - 1)
                        .toLowerCase().split("\\.");

                if (extensions.contains(parts[parts.length - 1])) {
                    banned = true;
                    bannedExtension = parts[parts.length - 1];
                }
            }
        }
    }

}
